package com.xnyzc.lhy.mis.service.impl.cms.user;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.base.Joiner;
import com.xnyzc.lhy.common.entity.Rv;
import com.xnyzc.lhy.common.exception.PangException;
import com.xnyzc.lhy.common.penum.EErrorCode;
import com.xnyzc.lhy.common.penum.cms.EVehicleType;
import com.xnyzc.lhy.common.penum.tab.ESidebar;
import com.xnyzc.lhy.common.penum.tab.ETab;
import com.xnyzc.lhy.common.util.CheckUtil;
import com.xnyzc.lhy.common.util.IDUtil;
import com.xnyzc.lhy.common.util.TokenUtil;
import com.xnyzc.lhy.mis.entity.dictionaries.OaSysDict;
import com.xnyzc.lhy.mis.entity.param.cms.OfficeParam;
import com.xnyzc.lhy.mis.entity.param.sidebar.UserPermissionResults;
import com.xnyzc.lhy.mis.entity.sidebar.OaSysSidebar;
import com.xnyzc.lhy.mis.entity.user.tab.OaTabPermission;
import com.xnyzc.lhy.mis.entity.user.tab.OaTabUser;
import com.xnyzc.lhy.mis.mapper.dictionaries.OaSysDictMapper;
import com.xnyzc.lhy.mis.mapper.sidebar.OaSysSidebarMapper;
import com.xnyzc.lhy.mis.mapper.user.tab.OaTabPermissionMapper;
import com.xnyzc.lhy.mis.mapper.user.tab.OaTabUserMapper;
import com.xnyzc.lhy.mis.service.cms.user.UserPermissionsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 用户关联权限
 * </p>
 *
 * @author wangshuo
 * @since 2019-08-28
 */
@Service
public class UserPermissionsServiceImpl implements UserPermissionsService {

    @Autowired
    private OaSysDictMapper oaSysDictMapper;

    @Autowired
    private OaTabPermissionMapper oaTabPermissionMapper;

    @Autowired
    private OaSysSidebarMapper oaSysSidebarMapper;

    @Autowired
    private OaTabUserMapper oaTabUserMapper;

    /**
     * 用户关联权限列表
     *
     * @return
     */
    @Override
    public Rv getUserPermissionsList(OfficeParam param) {
        String tag=TokenUtil.getTag();
        List<Long> userIdList=param.getUserIdList();
        if(userIdList.isEmpty()){
            throw PangException.create(EErrorCode.missingArg);
        }
        Integer haveSpecified=0;
        // 侧边栏
        List<OaSysDict> oaSysDictList=getOaSysDictList(tag);
        // 车辆关联
        List<OaSysDict> vehicleDictList=getVehicleDictList(tag);
        // tab栏
        List<OaTabPermission> oaTabPermissionList=getOaTabPermissionList(tag);
        List<OaSysDict> dictList =new ArrayList<>();
        List<OaSysDict> vehDictList =new ArrayList<>();
        List<OaTabPermission> oaTabList=new ArrayList<>();
        List<UserPermissionResults> vehicleResultsList=new ArrayList<>();
        List<UserPermissionResults> sidebarResultsList=new ArrayList<>();
        List<UserPermissionResults> tabResultsList=new ArrayList<>();
        if(userIdList.size()==1){
            // 侧边栏
            List<OaSysSidebar> sidebarList=new ArrayList<>();
            QueryWrapper<OaSysSidebar> sidebarWrapper = new QueryWrapper<>();
            sidebarWrapper.eq(OaSysSidebar.USER_ID, userIdList.get(0));
            sidebarList = oaSysSidebarMapper.selectList(sidebarWrapper);
            if(!sidebarList.isEmpty()){
                OaSysSidebar sidebar=sidebarList.get(0);
                haveSpecified=sidebar.getHaveSpecifiedVehicle();
                dictList=sysDictList(sidebar.getDictIds(),tag);
                vehDictList=sysDictList(sidebar.getDictAssociatedIds(),tag);
            }
            // tab栏
            QueryWrapper<OaTabUser> tabWrapper = new QueryWrapper<>();
            tabWrapper.eq(OaTabUser.USER_ID, userIdList.get(0));
            List<OaTabUser> tabList = oaTabUserMapper.selectList(tabWrapper);
            if (!tabList.isEmpty()) {
                List<Integer> tabIdList = new ArrayList<>();
                for (OaTabUser tab : tabList) {
                    tabIdList.add(tab.getTabId());
                }
                QueryWrapper<OaTabPermission> userTabWrapper = new QueryWrapper<>();
                userTabWrapper.in(OaTabPermission.TAB_ID, tabIdList);
                oaTabList = oaTabPermissionMapper.selectList(userTabWrapper);
            }
            for(OaTabPermission sys:oaTabPermissionList){
                UserPermissionResults res = new UserPermissionResults();
                res.setId(Long.valueOf(sys.getTabId()));
                res.setLabel(sys.getTabName());
                res.setSelected(0);
                if(!oaTabList.isEmpty()){
                    for(OaTabPermission dict:oaTabList){
                        if(sys.getTabId().equals(dict.getTabId())){
                            res.setSelected(1);
                        }
                    }
                }
                tabResultsList.add(res);
            }
            // 侧边栏
            sidebarResultsList=getAssociatedList(oaSysDictList,dictList);
            // 车型
            vehicleResultsList=getAssociatedList(vehicleDictList,vehDictList);
        }else{
            tabResultsList=getMultiSelectTab(oaTabPermissionList,tabResultsList);
            sidebarResultsList=getMultiSelectSidebar(oaSysDictList,sidebarResultsList);
            vehicleResultsList=getMultiSelectVehicle(vehicleDictList,vehicleResultsList);
        }
        Map<String,Object> resMap=new HashMap<>(16);
        resMap.put("vehicleResultsList",vehicleResultsList);
        resMap.put("sidebarResultsList",sidebarResultsList);
        resMap.put("haveSpecified",haveSpecified);
        resMap.put("tabResultsList",tabResultsList);
        return Rv.wrap(EErrorCode.success,resMap);
    }

    public  List<UserPermissionResults>  getMultiSelectVehicle(List<OaSysDict> dictList,List<UserPermissionResults> sidebarResultsList) {
        for(OaSysDict sys:dictList){
            UserPermissionResults res = new UserPermissionResults();
            res.setId(sys.getDictId());
            res.setLabel(sys.getLabel());
            res.setSelected(0);
            if(sys.getValue().equals(String.valueOf(EVehicleType.vehTypeEconomic.getValue()))){
                res.setSelected(1);
            }
            sidebarResultsList.add(res);
        }
        return sidebarResultsList;
    }

    public  List<UserPermissionResults>  getMultiSelectSidebar(List<OaSysDict> dictList,List<UserPermissionResults> sidebarResultsList) {
        for(OaSysDict sys:dictList){
            UserPermissionResults res = new UserPermissionResults();
            res.setId(sys.getDictId());
            res.setLabel(sys.getLabel());
            res.setSelected(0);
            if(sys.getValue().equals(String.valueOf(ESidebar.system.getValue()))||sys.getValue().equals(String.valueOf(ESidebar.car.getValue()))||sys.getValue().equals(String.valueOf(ESidebar.wallet.getValue()))){
                res.setSelected(1);
            }
            sidebarResultsList.add(res);
        }
        return sidebarResultsList;
    }

    public  List<UserPermissionResults>  getMultiSelectTab(List<OaTabPermission> oaTabPermissionList,List<UserPermissionResults> tabResultsList){
        for(OaTabPermission sys:oaTabPermissionList){
            UserPermissionResults res = new UserPermissionResults();
            res.setLabel(sys.getTabName());
            res.setId(Long.valueOf(sys.getTabId()));
            res.setSelected(0);
            if(sys.getTabId().equals(ETab.personal.getValue())){
                res.setSelected(1);
            }
            tabResultsList.add(res);
        }
        return tabResultsList;
    }

    /**
     * 查询字典
     * @param str
     * @param tag
     * @return
     */
    public List<OaSysDict> sysDictList(String str,String tag){
        String[] vehSplitVal = str.split(",");
        List<String> vehAsList = Arrays.asList(vehSplitVal);
        QueryWrapper<OaSysDict> vehDictWrapper = new QueryWrapper<>();
        vehDictWrapper.in(OaSysDict.DICT_ID, vehAsList);
        vehDictWrapper.eq(OaSysDict.TAG,tag);
        vehDictWrapper.orderByAsc(OaSysDict.SORT);
        return oaSysDictMapper.selectList(vehDictWrapper);
    }

    /**
     * 处理关联数据
     * @param dictList
     * @param vehDictList
     * @return
     */
    public List<UserPermissionResults> getAssociatedList(List<OaSysDict> dictList, List<OaSysDict> vehDictList){
        List<UserPermissionResults> resultsList=new ArrayList<>();
        for(OaSysDict sys:dictList){
            UserPermissionResults res = new UserPermissionResults();
            res.setId(sys.getDictId());
            res.setLabel(sys.getLabel());
            res.setSelected(0);
            if(!vehDictList.isEmpty()){
                for(OaSysDict dict:vehDictList){
                    if(sys.getDictId().equals(dict.getDictId())){
                        res.setSelected(1);
                    }
                }
            }
            resultsList.add(res);
        }
        return resultsList;
    }

    /**
     * 查询侧边栏
     *
     * @param tag
     * @return
     */
    private List<OaSysDict> getOaSysDictList(String tag) {
        QueryWrapper<OaSysDict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(OaSysDict.TYPE, "sidebar");
        queryWrapper.eq(OaSysDict.TAG,tag);
        List<OaSysDict> dictList = oaSysDictMapper.selectList(queryWrapper);
        return dictList;
    }

    /**
     * 查询车型
     *
     * @param tag
     * @return
     */
    private List<OaSysDict> getVehicleDictList(String tag) {
        QueryWrapper<OaSysDict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(OaSysDict.TYPE, "require_level");
        queryWrapper.eq(OaSysDict.TAG,tag);
        List<OaSysDict> dictList = oaSysDictMapper.selectList(queryWrapper);
        return dictList;
    }

    /**
     * 查询tab栏
     *
     * @param tag
     * @return
     */
    private List<OaTabPermission> getOaTabPermissionList(String tag) {
        QueryWrapper<OaTabPermission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(OaTabPermission.USER_TYPE, 0);
        queryWrapper.eq(OaTabPermission.TAG,tag);
        List<OaTabPermission> dictList = oaTabPermissionMapper.selectList(queryWrapper);
        return dictList;
    }

    /**
     * 用户关联权限
     *
     * @return
     */
    @Override
    public Rv getUserPermissionsSave(OfficeParam param) {
       Long sysUserId=TokenUtil.getTokenUserId();
        List<Long> userIdList=param.getUserIdList();
        List<Integer> sidebarIdList=param.getSidebarIdList();
        List<Integer> tabIdList=param.getTabIdList();
        List<Integer> vehicleIdList=param.getVehicleIdList();
        if(sidebarIdList.isEmpty()||tabIdList.isEmpty()||userIdList.isEmpty()||vehicleIdList.isEmpty()||CheckUtil.objIsEmpty(param.getHaveSpecified())){
            throw PangException.create(EErrorCode.missingArg);
        }
        String tag=TokenUtil.getTag();
        // 删除侧边栏
        QueryWrapper<OaSysSidebar> sidebarWrapper = new QueryWrapper<>();
        sidebarWrapper.in(OaSysSidebar.USER_ID, userIdList).eq(OaSysSidebar.TAG,tag);
        oaSysSidebarMapper.delete(sidebarWrapper);
        // 删除tab栏
        QueryWrapper<OaTabUser> tabWrapper = new QueryWrapper<>();
        tabWrapper.in(OaTabUser.USER_ID, userIdList).eq(OaTabUser.TAG,tag);
        oaTabUserMapper.delete(tabWrapper);
        String vehId = Joiner.on(",").join(vehicleIdList);
        String sidebarId = Joiner.on(",").join(sidebarIdList);
        Date date=new Date();
        // 新增
        for(Long user:userIdList){
            OaSysSidebar sidebar=new OaSysSidebar();
            sidebar.setUserId(user);
            sidebar.setDictIds(sidebarId);
            sidebar.setTag(tag);
            sidebar.setType("1");
            sidebar.setSidebarId(IDUtil.nextId());
            sidebar.setUpdateTime(date);
            sidebar.setUpdateUser(sysUserId);
            sidebar.setHaveSpecifiedVehicle(param.getHaveSpecified());
            sidebar.setDictAssociatedIds(vehId);
            sidebar.setCreateTime(date);
            sidebar.setCreateUser(sysUserId);
            oaSysSidebarMapper.insert(sidebar);
        }
        for(int i=0;i<tabIdList.size();i++){
            for(int j=0;j<userIdList.size();j++){
                OaTabUser tab=new OaTabUser();
                tab.setUserId(userIdList.get(j));
                tab.setUserType(0);
                tab.setTag(tag);
                tab.setTabId(tabIdList.get(i));
                tab.setLinkedId(IDUtil.nextId());
                tab.setUpdateTime(date);
                tab.setUpdateUser(sysUserId);
                tab.setCreateTime(date);
                tab.setCreateUser(sysUserId);
                oaTabUserMapper.insert(tab);
            }
        }
        return Rv.wrap(EErrorCode.updateSuccess);
    }

}
